package wf.source.hrm.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import wf.source.hrm.client.RedisClient;
import wf.source.hrm.jwt.JwtUtils;
import wf.source.hrm.jwt.Payload;
import wf.source.hrm.util.RsaUtils;

import javax.servlet.http.HttpServletRequest;
import java.security.PublicKey;
import java.util.Date;

@Component
public class LoginFilter extends ZuulFilter{
    @Autowired
    private RedisClient redisClient;

    private String[] excludeUris = new String[]{"/services/user/sso/login","/services/user/sso/register"};
    @Override
    public String filterType() {
        //登陆校验 在前置拦截
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        // 1）获取Zuul提供的请求上下文对象
        RequestContext ctx = RequestContext.getCurrentContext();
        // 2) 从上下文中获取request对象
        HttpServletRequest req = ctx.getRequest();
        for (String uri : excludeUris) {
            if (req.getRequestURI().equals(uri)){
                System.out.println("iiiiiiiiiiii请求与uri相等");
                return false;
            }
        }
        //返回true 过滤器生效
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        // 登录校验逻辑。
        // 1）获取Zuul提供的请求上下文对象
        RequestContext ctx = RequestContext.getCurrentContext();
        // 2) 从上下文中获取request对象
        HttpServletRequest req = ctx.getRequest();
        // 3) 从请求中获取token
        String token = req.getHeader("token");
        System.out.println(token);
        // 4) 判断
        if(token == null || "".equals(token.trim())){
            // 没有token，登录校验失败，拦截
            ctx.setSendZuulResponse(false);
            // 返回401状态码。也可以考虑重定向到登录页。
            ctx.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
            return null;
        }
        String jwtToken = redisClient.get(token);
        //@TODO 权限判断 403

        //过期前10分钟刷新
        PublicKey publicKey = RsaUtils.getPublicKey(LoginFilter.class.getClassLoader().getResource("hrm_auth_rsa.pub").getFile());
        Payload<Object> payload = JwtUtils.getInfoFromToken(jwtToken, publicKey);

        //过期时间
        Date expiration = payload.getExpiration();
        //刷新时间
        DateTime refreshTime = new DateTime(expiration).minusMinutes(10);
        //当前时间在刷新时间之后就要刷新一把
        if(refreshTime.isBefore(DateTime.now())){
            // 调用服务刷新  传入token，调用user里面服务（重新保存jwttoken）重新返回一个jwttoken
            System.out.println("iiiiiiiiiiii");
        }
        // 校验通过，可以考虑把用户信息放入上下文，继续向后执行
        ctx.addZuulRequestHeader("jwtToken",jwtToken);
        return null;
    }
}
